package com.jasongj.kafka.consumer;

import net.lingala.zip4j.core.ZipFile;
import net.lingala.zip4j.exception.ZipException;
import net.lingala.zip4j.model.ZipParameters;
import net.lingala.zip4j.util.Zip4jConstants;

import java.io.*;
import java.security.MessageDigest;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

public class WriteDownload {

    public static void main(String[] args) throws Exception {
         while(true) {
             writeTree();
         }
    }

    private static void copyFile(File source, File dest)
            throws IOException {
        InputStream input = null;
        OutputStream output = null;
        try {
            input = new FileInputStream(source);
            output = new FileOutputStream(dest);
            byte[] buf = new byte[1024];
            int bytesRead;
            while ((bytesRead = input.read(buf)) > 0) {
                output.write(buf, 0, bytesRead);
            }
        } finally {
            input.close();
            output.close();
        }
    }
    public static String getFileSHA512(File file) {
        String str = "";
        try {
            str = getHash(file, "SHA-512");
        } catch (Exception e) {
            e.printStackTrace();
        }
        return str;
    }
    public static String getHash(File file, String hashType) throws Exception {
        InputStream fis = new FileInputStream(file);
        byte buffer[] = new byte[1024];
        MessageDigest md5 = MessageDigest.getInstance(hashType);
        for (int numRead = 0; (numRead = fis.read(buffer)) > 0; ) {
            md5.update(buffer, 0, numRead);
        }
        fis.close();
        return toHexString(md5.digest());
    }
    public static String toHexString(byte b[]) {
        StringBuilder sb = new StringBuilder();
        for (byte aB : b) {
            sb.append(Integer.toHexString(aB & 0xFF));
        }
        return sb.toString();
    }

    public static void writeFileByBytes(String fileName, byte[] bytes, boolean append) throws IOException {
        try(OutputStream out = new BufferedOutputStream(new FileOutputStream(fileName, append))){
            out.write(bytes);
        }
    }
    static List<String> signatures = new ArrayList<String>();
    public static void writeTree() throws Exception {
        Date now = new Date();
        long time = 1*60*1000;//1分钟
        Date beforeDate = new Date(now .getTime() - time);//1分钟前的时间

        SimpleDateFormat dateFormatDay= new SimpleDateFormat("yyyy-MM-dd");
        SimpleDateFormat dateFormatHour= new SimpleDateFormat("yyyy-MM-dd-HH");
        SimpleDateFormat dateFormatMinute= new SimpleDateFormat("yyyy-MM-dd-HH-mm");
        SimpleDateFormat dateFormatSecond = new SimpleDateFormat("mmss");

        String  day = dateFormatDay.format( beforeDate );
        String  hour = dateFormatHour.format( beforeDate );
        String  minute = dateFormatMinute.format( beforeDate );
        String  second = dateFormatSecond.format(now);

        File dataFile = new File("d:\\log_dir\\"+hour+"\\"+minute);
        File downLoadFile = new File("d:\\download\\"+hour+"\\"+minute+"-down");
        File treeFile = new File("d:\\tree\\"+day+"\\"+hour);
        File hashFile = new File("d:\\download\\"+hour+"\\"+minute+"-down-hash");
        File downLoadDir = new File("d:\\download\\"+hour+"\\");
        File treeDir = new File("d:\\tree\\"+day+"\\");

        if (dataFile.exists()&&!downLoadFile.exists()) {
            if (!downLoadDir.isDirectory()) {
                downLoadDir.mkdir();
            }
            //判断文件是否存在，不存在的话创建
            if (!downLoadFile.exists()) {
                downLoadFile.createNewFile();
            }
            if (!treeDir.isDirectory()) {
                treeDir.mkdir();
                System.out.println(treeDir.getName());
                System.out.println(treeDir.getPath());
            }
            if (!treeFile.exists()) {
                System.out.println(treeFile.getName());
                treeFile.createNewFile();
            }

            //1、设置现在时间延时1分钟，copy延时1分钟的文件到下载目录
            copyFile(dataFile,downLoadFile);
            //2、获取copy文件sha-512值，将该值写校验文件
            String hashCode = getFileSHA512(downLoadFile);
            System.out.println(dataFile.getName() +" hash code is:"+hashCode);
            BufferedWriter out = new BufferedWriter(new OutputStreamWriter(
                    new FileOutputStream(hashFile)));
            out.write(hashCode);
            out.close();
            //3、打包copy文件和校验文件
            ZipFile zipFile = new ZipFile("d:\\download\\"+hour+"\\"+minute+"-down.zip");
            ArrayList filesToAdd = new ArrayList();
            filesToAdd.add(new File("d:\\download\\"+hour+"\\"+minute+"-down"));
            filesToAdd.add(new File("d:\\download\\"+hour+"\\"+minute+"-down-hash"));
            try {
                ZipParameters parameters = new ZipParameters();
                parameters.setCompressionMethod(Zip4jConstants.COMP_DEFLATE); // set compression method to deflate compression
                parameters.setCompressionLevel(Zip4jConstants.DEFLATE_LEVEL_NORMAL);
                zipFile.addFiles(filesToAdd, parameters);
            } catch (ZipException e) {
                e.printStackTrace();
            }
            //4、将2中的校验值生成merkle树，以小时为单位
            signatures.add(hashCode);
            System.out.println("signatures.size() is:"+signatures.size());
            if(signatures.size()!=1){
                MerkleTree leaf = new MerkleTree(signatures);
                byte[] serializedTree = leaf.serialize();
                writeFileByBytes("d:\\tree\\"+day+"\\"+hour,serializedTree,false);
            }
            File zipFileReadOnly = new File("d:\\download\\"+hour+"\\"+minute+"-down.zip");
            //5、设定下载文件为只读
           // zipFileReadOnly.setReadOnly();
        }
        //每小时清空一次merkle节点
        if("0000".equals(second)){
            if(signatures.size()!=1){
                signatures.clear();
            }
        }
    }
}



